<?php

namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\RoleMenuService;
use support\Service\RoleService;

class RoleLogic extends BaseLogic
{

    public function __construct()
    {
        self::$service = new RoleService();
    }

    /**
     * 角色列表(分页)
     * @return array
     */
    public static function getList()
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['name']) && $param['name']) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = self::$service::getListPage($where);
        return message($list);
    }

    public static function edit()
    {
        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (!isset($data['code']) || empty($data['code'])) {
            throw new ApiException('请输入角色标识');
        }
        if (!isset($data['name']) || empty($data['name'])) {
            throw new ApiException('角色名称');
        }
        if (!isset($data['note']) || empty($data['note'])) {
            throw new ApiException('角色备注');
        }
        if (!isset($data['sort']) || empty($data['sort'])) {
            throw new ApiException('请输入排序');
        }
        $save['code'] = trim($data['code']);
        $save['name'] = trim($data['name']);
        $save['note'] = $data['note'];
        $save['sort'] = $data['sort'];
        $save['status'] = $data['status'];
        unset($data['id']);
        if ($id == 0) {
            self::$service::add($save);
        } else {
            self::$service::save($save, $id);
        }
        return message();
    }

    /**
     * 角色列表
     * @return array
     */
    public static function getRoleList()
    {
        $list = self::$service::getRoleList();
        return message($list);
    }

    public static function getPermissionList($role_id)
    {
        if (!$role_id) return message([]);
        $list = self::$service::getPermissionList($role_id);
        return message($list);
    }

    public static function savePermission()
    {
        // 请求参数
        $roleId = request()->post('role_id', 0);
        $menuIds = request()->post('menu_id', []);
        if (!$roleId) {
            throw new ApiException('角色ID不能为空');
        }
        // 插入角色菜单关系数据
        $menuIds = is_array($menuIds) ? $menuIds : [];
        // 删除角色菜单关系数据
        RoleMenuService::delete($roleId);
        if (!$menuIds) return true;
        $list = [];
        foreach ($menuIds as $val) {
            $data = [
                'role_id' => $roleId,
                'menu_id' => $val,
            ];
            $list[] = $data;
        }
        RoleMenuService::insertBatch($list);
        return message();

    }


}
